﻿using Microsoft.AspNetCore.Mvc.ModelBinding;
using System.Collections.Generic;
using System.Linq;

namespace CustomForm.Common.Extensions
{
    public static class ModelStateExtensions
    {
        public static Dictionary<string, string> GetErrors(this ModelStateDictionary modelState)
        {
            //找到出错的字段以及出错信息
            return modelState.Where(m => m.Value.Errors.Any()).ToDictionary(x => x.Key, x => x.Value.Errors.Select(e => e.ErrorMessage).FirstOrDefault());
        }

        public static string GetError(this ModelStateDictionary modelState)
        {
            //找到出错的字段以及出错信息
            return modelState.Where(m => m.Value.Errors.Any()).Select(x => $"{x.Value.Errors.Select(e => e.ErrorMessage).FirstOrDefault()}").FirstOrDefault();
        }
    }
}
